package org.vison.wonfu.framework.test.mproxy.service;

import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.vison.wonfu.framework.test.mproxy.dao.SqlCmdDao;
import org.vison.wonfu.framework.test.mproxy.dao.entity.SqlCmdPO;
import org.vison.wonfu.framework.test.mproxy.req.SqlCmdReq;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Service
public class SqlCmdService {

    @Resource
    private SqlCmdDao sqlCmdDao;

    public void init(SqlCmdReq sqlCmdReq) {
        SqlCmdPO sqlCmdPO = new SqlCmdPO();
        sqlCmdPO.setDatabaseName(sqlCmdReq.getDbname());
        sqlCmdPO.setSqlFingerprint(sqlCmdReq.getSqlFingerprint());
        sqlCmdPO.setExecutionTime(sqlCmdReq.getExecutionTime());
        // md5(sqlCmdReq.getSqlFingerprint())
        sqlCmdPO.setSignature(sha256(sqlCmdReq.getSqlFingerprint()));
        sqlCmdDao.insert(sqlCmdPO);
    }

    private static String sha256(String input) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(input.getBytes(StandardCharsets.UTF_8));
            StringBuilder hexString = new StringBuilder(2 * hash.length);
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }



}
